package com.data.modules.quartz.job;

import com.alibaba.fastjson.JSONObject;
import com.data.common.entity.TaskQiYeWeiXinMsg;
import com.data.common.system.vo.DictModel;
import com.data.common.util.RestUtil;
import com.data.modules.feign.TaskService;
import com.data.modules.system.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * T310 data-boot 企业微信告警 通知
 * 定时统计 发送状态 为 发送失败 的消息积压统计 数量（通过数据字典 动态 可配置 此数量） 并进行 企业微信告警 通知
 * @author xiayuanpeng
 * @since 2022/3/31
 */
@Component
@Slf4j
public class MsgSumWarningJob implements Job {
    @Autowired
    @Lazy
    private TaskService taskService;
    @Autowired
    private ISysDictService sysDictService;

    @Value("${magic.sumErrorMsg-url:}")
    String sumErrorMsgUrl;
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //查询字典配置 发送失败消息数量阈值
        List<DictModel> dictModels = sysDictService.queryDictItemsByCode("sys_sms_sum");
        log.info("===========发送失败消息数量阈值===>{}",dictModels.get(0).getValue());
        //调用magic-api 查询sys_sms发送失败消息数量
        JSONObject jsonObject = RestUtil.get(sumErrorMsgUrl);
        Integer count = jsonObject.getJSONArray("data").getJSONObject(0).getInteger("errorSum");
        log.info("===========查询出发送消息失败数量===>{}",count);
        //失败消息数量超过阈值发消息告警
        if(count >= Integer.parseInt(dictModels.get(0).getValue())){
            TaskQiYeWeiXinMsg taskQiYeWeiXinMsg = new TaskQiYeWeiXinMsg();
            taskQiYeWeiXinMsg.setFeedbackCategoryCode(5000);
            taskQiYeWeiXinMsg.setThreshold(Integer.parseInt(dictModels.get(0).getValue()));
            taskQiYeWeiXinMsg.setCount(count);
            taskService.companyWeiXinSend(taskQiYeWeiXinMsg);
        }
    }
}
